from paste.script.command import Command

import paste
import os

from cpswarehouse.config.environment import load_environment

from cpswarehouse.lib.datacleaner import simple_word_replace,\
    simple_school_consolidate, regex_school_replace,\
    consolidate_by_unit

from cpswarehouse.model import SchoolDimension
from cpswarehouse.model import meta

               

class CpsCleanup(Command):
    # Parser configuration
    summary = "Cleanup the already imported cps data."
    usage = "<settings_ini>"
    group_name = "cpswarehouse"
    parser = Command.standard_parser(verbose=False)

    def command(self):
        #make sure the config file arg is set
        if(len(self.args) != 1):
            print self.parser.format_help()
            return
        
        #load the environment
        conf_filename = os.path.abspath(self.args[0])
        conf = paste.deploy.appconfig("config:%s" % conf_filename)
        load_environment(conf.global_conf, conf.local_conf)
        
        
        schools = meta.Session.query(SchoolDimension).all()

        for school in schools:

            new_school_name = simple_word_replace(school.school)
            new_school_name = regex_school_replace(new_school_name)

            school.school = new_school_name
            #meta.Session.save_or_update(school)

        meta.Session.flush()
        meta.Session.commit()

        #simple_school_consolidate()
        consolidate_by_unit()
